package cate.game.framework.common.compress;

import cate.game.play.part.PlaySide;
import easy.java.codec.JsonCodec;
import easy.java.codec.Md5Codec;
import easy.java.codec.ZlibCodec;
import easy.java.practice.errorcode.EcResult;
import lombok.experimental.UtilityClass;

import java.io.IOException;

@UtilityClass
public class PlaySideCompressHelper {

    public static EcResult<CompressedContent> compressEc(PlaySide ps) {
        EcResult<CompressedContent> r = new EcResult();
        try {
            r.data = compress(ps);
        } catch (Throwable cause) {
            r.fail(cause);
        }
        return r.success();
    }

    public static CompressedContent compress(PlaySide ps) throws IOException {
        CompressedContent cc = new CompressedContent();
        String psJsonStr = JsonCodec.instance().encodeString(ps);
        cc.setContent(ZlibCodec.instance().compressString(psJsonStr));
        cc.setMd5Sum(Md5Codec.instance().encode32(psJsonStr));
        return cc;
    }

    public static PlaySide uncompress(CompressedContent cc) throws IOException {
        String jsonStr = ZlibCodec.instance().uncompressString(cc.getContent());
        return JsonCodec.instance().decode(jsonStr, PlaySide.class);
    }

    public static EcResult<PlaySide> uncompressEc(CompressedContent cc) {
        EcResult<PlaySide> r = new EcResult<>();
        try {
            r.data = uncompress(cc);
        } catch (Throwable cause) {
            r.fail(cause);
        }
        return r.success();
    }
}
